package com.example.student.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.domain.pojo.StudentAnswers;
import com.example.common.domain.vo.QuestionVo;
import com.example.student.domain.Dto.AnswerSubmitDTO;
import com.example.common.domain.vo.PageWithAnswer;
import com.example.common.domain.vo.QuestionWithAnswerVO;
import com.example.student.mapper.StudentAnswersMapper;
import com.example.student.service.StudentAnswersService;
import jakarta.transaction.Transactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
@Slf4j
public class StudentAnswersServiceImpl extends ServiceImpl<StudentAnswersMapper, StudentAnswers> implements StudentAnswersService {

    @Autowired
    private StudentAnswersMapper studentAnswersMapper;


    @Override
    @Transactional
    public void batchSaveOrUpdate(String studentId, String homeworkId,
                                  List<AnswerSubmitDTO.AnswerItem> answerItems) {
        for (AnswerSubmitDTO.AnswerItem item : answerItems) {
            // 3. 构建查询条件
            LambdaQueryWrapper<StudentAnswers> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(StudentAnswers::getStudentId, studentId)
                    .eq(StudentAnswers::getHomeworkId, homeworkId)
                    .eq(StudentAnswers::getQuestionId, item.getQuestionId());

            // 4. 检查答案是否已存在
            StudentAnswers existAnswer = studentAnswersMapper.selectOne(queryWrapper);

            if (existAnswer == null) {
                // 4.1 不存在则新增
                StudentAnswers newAnswer = new StudentAnswers();
                newAnswer.setStudentId(studentId);
                newAnswer.setHomeworkId(homeworkId);
                newAnswer.setQuestionId(item.getQuestionId());
                newAnswer.setAnswer(item.getAnswer());
                studentAnswersMapper.insert(newAnswer);
            } else {
                // 4.2 存在则更新
                existAnswer.setAnswer(item.getAnswer());
                studentAnswersMapper.updateById(existAnswer);
            }
        }
    }

    @Override
    public PageWithAnswer<QuestionWithAnswerVO> getHomeworkWithAnswers(PageWithAnswer<QuestionWithAnswerVO> resultPage,
                                                                       String homeworkId, String studentId) {
        List<QuestionWithAnswerVO> questionWithAnswerVOs = new ArrayList<>();
        List<String> questionIds = resultPage.getRecords().stream()  // 获取所有题目ID
                .map(QuestionWithAnswerVO::getId)
                .collect(Collectors.toList());

        if (!questionIds.isEmpty()) {
            // 3. 查询学生答案
            List<StudentAnswers> studentAnswers = studentAnswersMapper.selectList(
                    new LambdaQueryWrapper<StudentAnswers>()
                            .eq(StudentAnswers::getStudentId, studentId)
                            .eq(StudentAnswers::getHomeworkId, homeworkId)
                            .in(StudentAnswers::getQuestionId, questionIds)
            );         // 根据题目ID查询学生答案

            // 4. 构建答案映射表
            Map<String, StudentAnswers> answerMap = studentAnswers.stream()
                    .collect(Collectors.toMap(
                            StudentAnswers::getQuestionId,
                            answer -> answer,
                            (oldValue, newValue) -> oldValue
                    ));       //题目id，及其对应的学生答案

            // 5. 组装带答案的题目VO
            for (QuestionVo questionVo : resultPage.getRecords()) {
                QuestionWithAnswerVO vo = new QuestionWithAnswerVO();
                BeanUtils.copyProperties(questionVo, vo);

                StudentAnswers answer = answerMap.get(questionVo.getId());
                if (answer != null) {
                    vo.set_corrected(answer.isCorrected());
                    vo.setStudentAnswer(answer.getAnswer());
                    vo.setScore(answer.getScore());
                }

                questionWithAnswerVOs.add(vo);
            }
        }

        resultPage.setRecords(questionWithAnswerVOs);
        return resultPage;
    }


}
